import subprocess
import os
import json


def modify_cfg(user, password, filename):
    try:
        with open(filename, 'r+', encoding='utf-8') as fp:
            j = json.loads(fp.read())
            j['db']['host'] = '127.0.0.1'
            j['db']['user'] = user
            j['db']['password'] = password

        with open(filename, 'w+', encoding='utf-8') as fp:
            json.dump(j, fp, ensure_ascii=False, indent=4)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    # get mysql user password
    user = ''
    password = ''
    sub = subprocess.Popen('sudo cat /etc/mysql/debian.cnf', shell=True, stdout=subprocess.PIPE)
    while sub.poll() is None:
        output = sub.stdout.readline().decode('utf-8')
        lst = output.split('=')
        if len(lst) == 2:
            if lst[0].strip(' ') == 'user':
                user = lst[1][:-1].strip(' ')
            if lst[0].strip(' ') == 'password':
                password = lst[1][:-1].strip(' ')

    print(f'user: {user}, password: {password}')

    # modify bmt tct cfg.json
    # modify_cfg(user, password, '/home/manager/prj/ZJ/bin/BMT1.0/cfg.json')
    modify_cfg(user, password, './cfg.json')

    # create database and init
    # os.system(f'mysql -u{user} -p{password} < /home/manager/prj/ZJ/bin/BMT1.0/sql/bmt.sql')
    # os.system(f'mysql -u{user} -p{password} < ./sql/tct.sql')
    # os.system(f'mysql -u{user} -p{password} < ./sql/cfg.sql')
